<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    destroyOnClose
    :title="getTitle"
    width="70%"
    @ok="handleSubmit"
  >
    <Spin :spinning="loading">
      <BasicForm @register="registerForm" @field-value-change="handleChangeFeild">
        <!-- <template #modType="{ model, field }">
          <RadioButtonGroup
            v-model:value="model[field]"
            @change="changeModtype"
          
          />
        </template> -->
      </BasicForm>
      <div class="mt-2 p-4" v-if="isUpdate">
        <!-- <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 24px;
          "
        >
          <span style="font-weight: 550"> 菜单权限</span>
          <a-button type="primary" class="ml-2" @click="addAuthHandle">添加</a-button>
        </div>
        <BasicTable @register="registerTable">
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action'">
              <TableAction
                :actions="[
                  {
                    icon: 'clarity:note-edit-line',
                    label: '编辑',
                    onClick: handleEdit.bind(null, record),
                  },
                  {
                    icon: 'ant-design:delete-outlined',
                    label: '删除',
                    color: 'error',
                    popConfirm: {
                      title: '是否确认删除',
                      placement: 'left',
                      confirm: handleDelete.bind(null, record),
                    },
                  },
                ]"
              />
            </template>
          </template>
        </BasicTable> -->
        <!-- 绑定菜单则不显示控制按钮 -->
        <!--  v-if="actionAuths && isModelAuth && !isModelBind" -->
        <ActionAuth
          :moduleId="moduleId"
          :data="actionAuths"
          @success="handleSuccess"
          :isModelBind="isModelBind"
        />
      </div>

      <AddAuthModal @register="registerModal" @success="handleSuccess" />
    </Spin>
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref, nextTick } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { Spin } from 'ant-design-vue';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useModal } from '/@/components/Modal';
  import {
    useTable,
    // TableAction, BasicTable
  } from '/@/components/Table';
  import AddAuthModal from './AddAuthModal.vue';
  import ActionAuth from './ActionAuth.vue';

  import { formSchema, columnsAuth } from './menu.data';
  import { getMenuTree, addMenuApi, updateMenuApi, getMenuItemApi } from '/@/api/admin/menu';
  import { deleteModuleAuthApi } from '/@/api/admin/auth';

  export default defineComponent({
    name: 'MenuDrawer',
    components: {
      Spin,
      BasicDrawer,
      BasicForm,
      // BasicTable,
      // TableAction,
      AddAuthModal,
      ActionAuth,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const loading = ref(false);
      const isUpdate = ref(false);
      const isModelAuth = ref(false);
      const isModelBind = ref(true);
      const moduleId = ref();
      let updateInfo = {};

      const actionAuths = ref<any>();
      const { createMessage } = useMessage();

      const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
        labelWidth: 160,
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: { lg: 12, md: 24 },
      });

      async function getMenuItem(moduleId) {
        const res = await getMenuItemApi(moduleId);
        const { module, moduleUserTypes, usingHandles } = res;

        actionAuths.value = usingHandles || [];
        return { module, moduleUserTypes, usingHandles };
      }

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        loading.value = true;

        setDrawerProps({ confirmLoading: true });
        isUpdate.value = !!data?.isUpdate;
        if (unref(isUpdate)) {
          moduleId.value = data.record.id;

          const { module } = await getMenuItem(moduleId.value);
          updateInfo = module;
          // isModelAuth.value = module.modType === 1;
          isModelBind.value = Boolean(module.listModelId);

          module.extMeta = JSON.stringify(module.extMeta || '{}');

          nextTick(() => {
            setFieldsValue(module);

            if (module.modelClassify) {
              //  需要初始化重置
              setFieldsValue({ listModelId: module.listModelId, path: module.path });
            }
          });
        } else {
          let parentId = data.record.id;
          moduleId.value = '';
          setFieldsValue({
            parentId,
          });
        }
        const children = await getMenuTree();
        console.log(
          '%cchildren===>165： ',
          'background: rgb(23, 197, 237,.6); color: #ff5023; font-size:18px;font-weight:700',
          children,
        );

        updateSchema([
          {
            field: 'moduleId',
            ifShow: unref(isUpdate),
          },
          {
            field: 'parentId',
            componentProps: {
              fieldNames: {
                children: 'children',
                label: 'name',
                value: 'id',
              },
              treeData: [{ name: '根菜单', children, id: '-1' }],
            },
          },
        ]);
        loading.value = false;
        setDrawerProps({ confirmLoading: false });
      });
      // , { setTableData }
      const [registerTable] = useTable({
        columns: columnsAuth,
        pagination: false,
        striped: false,
        bordered: true,
        showIndexColumn: false,
        canResize: false,
        actionColumn: {
          width: 200,
          title: '操作',
          dataIndex: 'action',
          fixed: undefined,
        },
      });

      const [registerModal, { openModal }] = useModal();

      const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));
      function toJson(str) {
        try {
          return JSON.parse(str || '{}');
        } catch (e) {
          return {};
        }
      }
      async function handleSubmit() {
        try {
          loading.value = true;
          const values = await validate();
          setDrawerProps({ confirmLoading: true });

          const apiFn = unref(isUpdate) ? updateMenuApi : addMenuApi;
          values.typeFlag = 0;
          values.client = 0;
          if (!unref(isUpdate)) {
            values.typeRight = 1;
            values.modRight = 1;
          }
          if (!values.modelClassify) {
            values.listModelId = null;
            values.modelClassify = null;
          }
          const extMeta = toJson(values.extMeta);

          const params = Object.assign(updateInfo, values, { extMeta });

          await apiFn(params);
          createMessage.success('操作成功');
          closeDrawer();
          emit('success');
        } finally {
          loading.value = false;
          setDrawerProps({ confirmLoading: false });
        }
      }

      function handleEdit(record: Recordable) {
        openModal(true, {
          record,
          isUpdate: true,
        });
      }

      async function handleDelete(record: Recordable) {
        const { moduleId, userFlag } = record;
        await deleteModuleAuthApi(moduleId, userFlag);
        createMessage.success('操作成功');
        getMenuItem(moduleId);
      }

      function addAuthHandle() {
        openModal(true, {
          record: { moduleId: moduleId.value },
          idupdate: false,
        });
      }

      function handleSuccess() {
        getMenuItem(moduleId.value);
      }
      function changeModtype(v) {
        isModelAuth.value = v === 1;
      }
      function handleChangeFeild(key, value) {
        if (key === 'modelClassify') {
          isModelBind.value = !!value;
        }
        if (key === 'modType') {
          changeModtype(value);
        }
      }

      return {
        loading,
        isUpdate,
        getTitle,
        actionAuths,
        moduleId,
        isModelAuth,
        isModelBind,
        registerDrawer,
        registerForm,
        registerTable,
        registerModal,
        handleEdit,
        handleSubmit,
        handleDelete,
        addAuthHandle,
        handleSuccess,
        changeModtype,
        handleChangeFeild,
      };
    },
  });
</script>
